package com.clouddrive.File;

import com.clouddrive.User;
import com.clouddrive.dao.impl.UserServiceImpl;
import com.clouddrive.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

@MultipartConfig
@WebServlet(value = "/uploadfile", name = "UploadFile")
public class UploadFile extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Cookie[] cookies = request.getCookies();
        User nowUser = userService.GetUserByCookie(cookies);

        Part filepart = request.getPart("myfile");
        String filename = filepart.getSubmittedFileName();
        System.out.println(filename);
        if (filename.equals("")) {
            System.out.println("请先选择文件");
            return;
        }
        String fs = File.separator;
        String path = request.getServletContext().getRealPath("/");
        path = path.endsWith(fs) ? path : path + fs;
        path += ".." + fs + "upload" + fs + nowUser.getEmail() + fs;
        //System.out.println(path);
        File folder = new File(path);
        if (!folder.exists() && !folder.isDirectory()) {
            if(folder.mkdirs()){
                System.out.println("文件夹已创建");
            }
        } else {
            System.out.println("文件夹已存在");
        }
        try {
            filepart.write(path + filename + ".Suzuran");
        } catch (IOException e) {
            System.out.println("文件写入出现问题");
            throw new RuntimeException(e);
        }
        response.sendRedirect(request.getContextPath() + "/disc.html");
    }
}
